<template>
    <div class="w-2/3 mx-auto mt-5">
        <div class="p-3 border rounded-md border-solid border-gray-300">
            <Header :addTodo="addTodo"></Header>
            <List :todos="todos" :deleteTodo="deleteTodo" :updateTodo="updateTodo"></List>
            <Footer :todos="todos" :checkAll="checkAll" :clearCheckTodos="clearCheckTodos"></Footer>
        </div>
        {{ todos }}
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs, watch, onMounted } from 'vue'
import Header from '../components/todoList/header.vue'
import List from '../components/todoList/list.vue'
import Footer from '../components/todoList/footer.vue'
import type { Todo } from '../types/todo'
import { saveTodos, readTodos } from '../utils/localStorageUtils'

export default defineComponent({
    components: {
        Header,
        List,
        Footer
    },
    setup () {
        const state = reactive<{todos: Todo[]}>({
            // todos: [
            //     {
            //         id: 1,
            //         title: '大众',
            //         isCompleted: false
            //     },{
            //         id: 2,
            //         title: '本田',
            //         isCompleted: true
            //     },
            // ]
            todos: []
        })

        onMounted(() => {
            setTimeout(() => {
                state.todos = readTodos()
            }, 100);
        })

        // 添加数据的方法
        const addTodo = (todo: Todo) => {
            state.todos.unshift(todo)
        }

        // 删除数据的方法
        const deleteTodo = (index: number) => {
            state.todos.splice(index, 1)
        }

        // 修改todo的computed属性状态
        const updateTodo = (todo: Todo, isCompleted: boolean) => {
            todo.isCompleted = isCompleted
        }

        // 全选或全不选
        const checkAll = (isCompleted: boolean) => {
            // 遍历数组
            state.todos.forEach(todo => {
                todo.isCompleted = isCompleted
            })
        }

        // 删除多个选中的数据
        const clearCheckTodos = () => {
            state.todos = state.todos.filter(todo => !todo.isCompleted)
        }

        // watch(()=>state.todos,(value)=>{
        //     // 保存到浏览器缓存中
        //     saveTodos(value)
        // },{deep: true})

        watch(() => state.todos, saveTodos, {deep: true})

        return {
            ...toRefs(state),
            addTodo,
            deleteTodo,
            updateTodo,
            checkAll,
            clearCheckTodos,
        }

        
    }
})
</script>

<style lang="scss">
*, ::before, ::after{
    box-sizing: border-box;
    border-width: 0;
}

body,html,div,ul,li,h1,h2,h3,h4,h5,p,span{
    margin: 0;
    padding: 0;
}

ul,li{
    list-style-type: none;
}
</style>